<?php
namespace App\Controller;
use Think\Controller;
class UserController extends Controller {
    public function index(){
    	$user = M('_user');
    	$list=$user->find();
	
		$this->ajaxReturn($list,'JSON');
    }

    public function register(){
    	$user = M('_user');
    	$data['phone'] = I('post.phone');
    	$data['pwd'] = I('post.pwd');
    	$data['nickname'] = I('post.nickname');

    	// 查重复
    	$map['phone'] = $data['phone'];
    	$flag = $user->where($map)->find();
    	if ($flag) {
    		$res['code'] = "-1";
    		$res['msg'] = "账户已存在";
    		$this->ajaxReturn($res,'JSON');
    	} else{

    		$res['code'] = $user->add($data);
    		$res['msg'] = "注册成功";
    		$this->ajaxReturn($res,'JSON');
    	}
    }

    public function login($phone, $pwd){
        $user = M('_user');
        $map['phone'] = $phone;
        $map['pwd'] = $pwd;

        $res['user'] = $user->where($map)->find();
        if ($res['user'] != null) {
            $res['code'] = "1";
            $res['msg'] = "登陆成功";
        } else{
            $res['code'] = "-2";
            $res['msg'] = "用户或密码错误";
        }
        $this->ajaxReturn($res,'JSON');
    }

    public function getUserInfo($id){
        $user = M('_user');
        $map['id'] = $id;

        $res = $user->where($map)->find();
        if ($res!= null) {
            $this->ajaxReturn($res,'JSON');
        }
    }

    public function updateUserInfo(){
        $User = M('_user');
        $map['id'] = I('post.id');
        $data['nickname'] = I('post.nickname');
        $data['gender'] = I('post.gender');
        $data['image'] = I('post.image');
        //  $map['id'] = 16;
        // $data['nickname'] = "QinX";
        // $data['gender'] = "男";
        // $data['image'] = "test";
        // echo "1";

        if($data['image'] == ""){
            $data['image'] = 'default';
        }

         $flag = $User->where($map)->save($data);
        

        if ($flag != null) {
            $res['code'] = "1";
            $res['msg'] = "更新成功";
            $this->ajaxReturn($res,'JSON');
        } else{
            $res['code'] = "-3";
            $res['msg'] = "更新失败";
            $this->ajaxReturn($res,'JSON');
        }
    }

    public function resetPwd($id, $originPwd, $newPwd){
        $User = M('_user');
        $map['id'] = $id;
        $map['pwd'] = $originPwd;

        $data['pwd'] = $newPwd;

        $r = $User->where($map)->find();
        if ($r = null) {
            $res['code'] = "-2";
            $res['msg'] = '原密码错误';
            $this->ajaxReturn($res,'JSON');
        } else{
            $User->where($map)->save($data);
            $res['code'] = "4";
            $res['msg'] = '已更新';
            $this->ajaxReturn($res,'JSON');   
        }
    }
}